# ------------------------------------------------------------------------------
# Builds chief complaint ed encounter cohort
# Author: Cassidy Shubatt <cshubatt@gmail.com>
# To run: bash 04_build_cc_df.sh
# ------------------------------------------------------------------------------

# Libraries ----------------------------------------------------------
library(here)
library(yaml)
library(feather)
library(dplyr)
library(data.table) # setnames
library(readr) # write_rds

u <- modules::use(here::here("lib", "util.R"))

# Load Data --------------------------------------------------------------------
message("Loading data...")
overnight_lab <- ""
paths <- read_yaml(here("lib", "filepaths.yml"))
ed_enc <- read_feather(paths$cohort$ed_enc_xwalk) %>%
  setnames("enc_row_id", "ed_enc_id") %>%
  mutate(ptid = as.numeric(ptid))

# Chief Complaints -------------------------------------------------------------
message("Getting chief complaints...")
cc_cols <- names(ed_enc)[grepl("cc", names(ed_enc))]
keep_cols <- c("ptid", "ed_enc_id", "chief_complaint_sup", cc_cols)

ed_enc_cc <- ed_enc %>%
  select(all_of(keep_cols))

# Save -------------------------------------------------------------------------
message("Saving chief complaints to ", paths$analysis$cc, "...")
write_rds(ed_enc_cc, paths$analysis$cc)

message("Done.")
